package filter

import (
	"github.com/project-flogo/core/activity"
	"github.com/project-flogo/core/data/metadata"
)

func init() {
	_ = activity.Register(&Activity{}, New)
}

var activityMd = activity.ToMetadata(&Settings{}, &Input{}, &Output{})

func New(ctx activity.InitContext) (activity.Activity, error) {
	s := &Settings{}
	err := metadata.MapToStruct(ctx.Settings(), s, true)
	if err != nil {
		return nil, err
	}

	filter, err := NewFilter(s.Filter)
	if err != nil {
		return nil, err
	}

	act := &Activity{
		filter: filter,
	}

	return act, nil
}

// Activity is an Activity that is used to Filter a message to the console
type Activity struct {
	filter Filter
}

// Metadata returns the activity's metadata
func (a *Activity) Metadata() *activity.Metadata {
	return activityMd
}

// Eval implements api.Activity.Eval - Filters the Message
func (a *Activity) Eval(ctx activity.Context) (done bool, err error) {

	filter := a.filter

	input := Input{}
	err = ctx.GetInputObject(&input)
	if err != nil {
		return false, err
	}

	data := input.Data
	cond := filter.Apply(data)

	done = cond
	output := Output{
		Data: data,
	}
	err = ctx.SetOutputObject(&output)
	if err != nil {
		return false, err
	}

	return done, nil
}
